var pageParams;
function refresh() {
    $("#dataTable").bootstrapTable("removeAll");
    $("#dataTable").bootstrapTable('refresh');
}
function showSubList(id,code){
    $$.goUrl("/iot/calc/calc_list.html?thirdMenuCode=CalcRules&mhDataId="+id+"&pId="+id+"&pCode="+code+"");

}


function deleteData() {
    layer.confirm('确定要删除这条数据吗？',
        {icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, function (index) {
            var rows = $("#dataTable").bootstrapTable('getSelections');
            var rowIds = [];
            for (var i = 0; i < rows.length; i++) {
                rowIds.push(rows[i].id);
            }
            $$.ajax({
                url: "/rest/IotCalcRuleBusiness/remove",
                data: {
                    id: rowIds.join(',')
                },
                success: function () {
                    refresh();
                }
            });
            layer.close(index);
        });
}

function addData() {
    layer.open({
        move: false,
        type: 2,
        title: '新建',
        area: ['800px', '620px'],
        content: 'calc_rule_add.html',
        btn: ['保存', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refresh();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
}

function modifyCatalog(data) {
    var rows = $("#dataTable").bootstrapTable('getSelections');
    var rowIds = [];
    for (var i = 0; i < rows.length; i++) {
        rowIds.push(rows[i].id);
    }
    var catalogId=data.DataSourceID;
    if(catalogId==1){
        catalogId=-1;
    }
    $$.ajax({
        url: "/rest/IotCalcRuleBusiness/modifyBatch",
        data: {
            catalogId: catalogId,
            id: rowIds.join(",")
        },
        success: function (data) {
            layer.msg('设置成功', {time: 2000});
        }
    });
    refresh();
}

function editData(rowId) {
    layer.open({
        move: false,
        type: 2,
        title: '新建',
        area: ['800px', '620px'],
        content: 'calc_rule_update.html?rowId=' + rowId,
        btn: ['保存', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refresh();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
}

//搜索以前将页码换成第一页
function searchInit() {
    var options = $("#dataTable").bootstrapTable("getOptions");
    options.pageNumber = 1;
    $("#dataTable").bootstrapTable('refreshOptions', options);
}

function initSearchEvent() {

    $("#serachBtn").click(function () {
        searchInit();
        refresh();
    });
    $('#serachBtn').bind('keypress', function (e) {


        if (e.keyCode == 13) {
            searchInit();
            refresh();
        }
    });
    $('#seachValue1').bind('keypress', function (e) {

        if (e.keyCode == 13) {
            searchInit();
            refresh();
        }
    });
    $('#seachValue2').bind('keypress', function (e) {

        if (e.keyCode == 13) {
            searchInit();
            refresh();
        }
    });
    $("#searchReset").on("click", function () {
        //$("#searchForm")[0].reset();
        $("#searchForm input[type='text']").val("");
    });

    //新建弹框
    $("#add-btn").on('click', function () {
        addData();
    });
}


function refreshTree() {
    $("#treeParent").empty();
    $("#treeParent").append('<div id="authorityTable"></div>');
    initTree();
}

function initTree() {
    var DataSource = [];
    $$.ajax({
        url: "/rest/IotCalcCatalogBusiness/listAllSort",
        async: false,
        data: {
            menuCode: ""
        },
        success: function (data) {
            //console.log("listByMenuId:"+JSON.stringify(data));
            DataSource = data;
        }
    });


    var source = {
        dataType: "json",
        dataFields: [{
            name: "stockName",
            type: "string",

        }, {
            name: "DataSourceID",
            type: "string",

        }, {
            name: 'children',
            type: 'array'
        }, {
            name: 'expanded',
            type: 'bool'
        }],
        hierarchy: {
            root: 'children'
        },
        id: 'DataSourceID',
        localData: DataSource
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    var iHeight = $("#rightCont").height() - 30;
    // create Tree Grid
    $("#authorityTable").jqxTreeGrid({
        source: dataAdapter,
        width: '100%',
        altRows: true,
        selectionMode: "singleRow",
        height: iHeight,
        theme: 'bootstrap',
        showToolbar: false,
        enableHover: true,
        columns: [{
            text: "分类",
            align: "center",
            dataField: "stockName",
            cellsRenderer: function (row, column, value, rowData) {
                var container ="";
                if(rowData.DataSourceID==-1 || rowData.DataSourceID==-9999){

                    container = '<span style="width: 100%; height: 100%;">';
                    var data = '<span class="tree-item-text" title=" ' + value + ' ">' + value + '</span>'
                    var option = '<span class="rt tree-item-opt hidden">' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-plus" onclick="addClassify(event,\'' + rowData.DataSourceID + '\')"></i></a>' +
                        '</span>';
                    container += data;
                    container += option;
                    container += "</span>";
                }else{
                    container = '<span style="width: 100%; height: 100%;">';
                    var data = '<span class="tree-item-text" title=" ' + value + ' ">' + value + '</span>'
                    var option = '<span class="rt tree-item-opt hidden">' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-plus" onclick="addClassify(event,\'' + rowData.DataSourceID + '\')"></i></a>' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-pencil" onclick="editClassify(event,\'' + rowData.DataSourceID + '\')"></i></a>' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-trash" onclick="delClassify(event,\'' + rowData.DataSourceID + '\')"></i></a></span>';
                    container += data;
                    container += option;
                    container += "</span>";



                }

                return container;
            },
        }],
        ready:function () {
            classifyOpt();
        }
    });
    //收起子菜单鼠标悬浮操作
    $("#authorityTable").on('rowCollapse', function (event) {

    });
    //展开子菜单鼠标悬浮操作
    $("#authorityTable").on('rowExpand', function (event) {
    });
}

(function (undefined) {
    "use strict"
    var _global;

    function result(args, fn) {
        var argsArr = Array.prototype.slice.call(args);
        if (argsArr.length > 0) {
            return argsArr.reduce(fn);
        } else {
            return 0;
        }
    }

    var collectionList = {
        columnsInit: function () {
            return [
                {
                    field: 'status',
                    title: '序号',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },

                {field: "dataTable", title: "数据存储表格", sortable: true},
                {field: "dataCode", title: "数据编码"},
                {field: "dataName", title: "名称名称"},
                {field: "dataColumn", title: "数据存储列"},
                {field: "dataScale", title: "精度"},
                {field: "catalogName", title: "分类名称"},
                {field: "rowSort", title: "排序号"},
                {
                    field: 'status',
                    title: '状态',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return [
                                '<span class="sys-type-bg pro-status-green">正常</span>'
                            ];
                        }
                        return [
                            '<span class="sys-type-bg pro-status-red">禁用</span>'
                        ];
                    }
                },
                {
                    field: 'optionDel',
                    checkbox: true
                }, {
                    field: 'option',
                    title: '操作',
                    width: 80,
                    align: 'center',
                    formatter: function (value, row, index) {
                        return [

                            '<div class="opt-dropdown tb-opt-div"><a class="tb-opt-icon" href="javascript:void(0)">操作 <i class="glyphicon glyphicon-triangle-bottom"></i></a>',
                            '<ul class="opt-dropdown-menu opt-dropdown-menu-bottom">',
                            '<li><a href="javascript:editData(\'' + row.id + '\')" title="编辑">',
                            '<i class="glyphicon glyphicon-pencil"></i><em> 编辑</em></a></li>',
                            '<li><a href="javascript:showSubList(\'' + row.id + '\',\'' + row.dataCode + '\')"><i class="glyphicon glyphicon-th-list"></i><em> 计算规则</em></a></li></ul></div>'






                        ].join('');
                    }
                }]
        },
        gridInit: function (columns) {
            return $("#dataTable").bootstrapTable({
                method: "post",
                contentType: "application/x-www-form-urlencoded",
                url: $$.restServerUrl + '/bootstrap/basegrid/IotCalcRuleBusiness/list',
                columns: columns,
                undefinedText: '-',
                striped: 'true',
                classes: 'table table-hover qxttable',
                pagination: 'true',
                clickToSelect: true,
                singleSelect: false,
                sidePagination: "server",
                queryParamsType: "page",
                sortSide: 'client',
                sortable: true,
                pageNumber: 1,
                pageSize: 10,
                idField: 'id',
                silentSort: true,
                pageList: [
                    10, 20, 50, 100
                ],
                onClickRow: function (row, $element, field) {
                    $("#dataTable").bootstrapTable("uncheckAll");
                },
                queryParams: function queryParams(params) {   //设置查询参数

                    var args = {};
                    var dataCatalog = $("#dataCatalog").val();



                    if (dataCatalog != "" && dataCatalog != '-9999') {
                        args.c_catalogId_1 = dataCatalog;
                    }

                    args.c_dataCode_7 = $("#seachValue1").val();
                    args.c_dataName_7 = $("#seachValue2").val();
                    args.page = params.pageNumber - 1; //    params.pageNumber
                    args.pageSize = params.pageSize;     //params.pageSize
                    args.isPage = 1;
                    //args.order=orderStr;
                    var paramStr = JSON.stringify(args);

                    //alert(params.pageNumber+":"+params.pageSize);
                    //alert(orderStr);
                    var param = {
                        params: paramStr
                    };
                    return param;
                },
                onPostBody: function () {
                    $(".opt-dropdown").each(function (index, data) {
                        var _this = this;
                        $(this).hover(function () {
                            $(_this).find(".opt-dropdown-menu").show();
                        }, function () {
                            $(_this).find(".opt-dropdown-menu").hide();
                        })
                    });
                    var minHeight = $("#rightCont").height() -30;
                    var maxheight = $("#dataTable").height() + 100;
                    if(maxheight < minHeight){
                        $("#authorityTable").jqxTreeGrid({
                            height:minHeight
                        })
                    } else if(maxheight > minHeight){
                        $("#authorityTable").jqxTreeGrid({
                            height:maxheight
                        })
                    }
                }
            })

        },
        dataInit: function () {
            return []
        }
    }

    // 将插件对象暴露给全局对象
    _global = (function () {
        return this || (0, eval)('this');
    }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = collectionList;
    } else if (typeof define === "function" && define.amd) {
        define(function () {
            return collectionList;
        });
    } else {
        !('plugin' in _global) && (_global.collectionList = collectionList);
    }
}());
$(function () {
    pageParams=$$.getQueryString();
    //tree
    initTree();

    initSearchEvent();

    //右侧表格
    $('#deviceCode').focus();
    //重置表单
    $("#searchReset").on("click", function () {
        $("#searchForm")[0].reset();
    });
    //渲染表格
    var columns = collectionList.columnsInit();
    var table = collectionList.gridInit(columns);
    var datas = collectionList.dataInit();
    $("#dataTable").bootstrapTable("append", datas);
    //点击删除按钮信息弹出框
    $("#del-btn").click(function () {
        var len = $("#dataTable input:checked").length;
        if (len == 0) {
            //未选中数据提示框
            layer.msg('请选择数据', {time: 1000});
        } else {
            deleteData();
        }

    });
    //点击左边tree,右侧table refresh
    $("#authorityTable").on('rowSelect', function (event) {
        var eo = window.event || arguments.callee.caller.arguments[0];
        var target=eo.target || eo.srcElement
        //googlechrome
        if(window.event){
            var tagName = target.tagName;
            //alert(event.source);
            //如果是单击分类信息
            if (tagName == "SPAN" || tagName == "TD") {
                var row = event.args.row;
                $("#dataCatalog").val(row.DataSourceID);
                refresh();
            }
        }else{
            //console.log(" eo.target "+eo.target);
            //console.log(" eo.srcElement "+eo.srcElement);
            //console.log(" target.value "+target.);
            //console.log(" target.tagName "+target.tagName);
            //console.log("firforxeo.target.tagName:"+eo.srcElement.tagName+"value:"+eo.srcElement.value);

            //firefox
            var tagName = target.tagName;
            //console.log("eo.target.tagName:"+eo.target.tagName);

            var row = event.args.row;
            $("#dataCatalog").val(row.DataSourceID);
            refresh();
        }


    });

    //设置分类
    $("#catalog-btn").on('click', function () {
        var len = $("#dataTable input:checked").length;
        if (len == 0) {
            //未选中数据提示框
            layer.msg('请选择数据', {time: 2000});
        } else {


            layer.open({
                move: false,
                type: 2,
                title: '设置采集点分类',
                area: ['900px', '500px'],
                content: 'calc_catalog_select.html',
                btn: ['确定', '取消'],
                btnAlign: 'c',
                yes: function (index, layero) {
                    var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var ret = openWin.yesOperator();
                    if (ret == null) {

                    } else {


                        modifyCatalog(ret);
                        layer.close(index);
                    }

                }, cancel: function (index) {
                    layer.close(index);
                }
            });
        }
    });

})

function classifyOpt() {
    $("#authorityTable").on("mouseover mouseout","tr",function(event){
        console.log(event.type);
        if(event.type == 'mouseover'){
            $(this).find('.rt').removeClass('hidden');
        }else{
            $(this).find('.rt').addClass('hidden');
        }
    });
}





//新建分类弹出框
function addClassify(e, data) {
    if(data==-1 || data==-9999){
        data=0;
    }
    e = e || window.event;
    layer.open({
        move: false,
        type: 2,
        title: '新建分类',
        area: ['500px', '200px'],
        content: 'calc_catelog_add.html?rowId=' + data,
        btn: ['确定', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {


            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refreshTree();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

//编辑分类弹出框
function editClassify(e, data) {

    e = e || window.event;
    layer.open({
        move: false,
        type: 2,
        title: '编辑分类',
        area: ['500px', '200px'],
        content: 'calc_catelog_update.html?rowId=' + data,
        btn: ['确定', '取消'],
        btnAlign: 'c',
        yes: function (index, layero) {
            var openWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var ret = openWin.yesOperator();
            if (ret) {
                layer.close(index);
                refreshTree();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

//删除分类弹出框
function delClassify(e, data) {
    e = e || window.event;
    layer.confirm('确定要删除分类吗？',
        {icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, function (index) {

            $$.ajax({
                url: "/rest/IotCalcCatalogBusiness/remove",
                data: {
                    id: data
                },
                success: function () {
                    layer.close(index);
                    refreshTree();
                }
            });

        });
    e.stopPropagation();
}




